package cn.antcore.common.security.mobile;

import cn.antcore.service.AuthService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * 短信验证码模式
 * <br>
 * Created by Hong 2024/5/28
**/
public class MobileAuthenticationProvider implements AuthenticationProvider {

    private final AuthService authService;

    public MobileAuthenticationProvider(AuthService authService) {
        this.authService = authService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MobileAuthenticationToken unauthenticatedToken = (MobileAuthenticationToken) authentication;
        String mobile = (String) unauthenticatedToken.getPrincipal();
        String code = unauthenticatedToken.getCode();

        UserDetails userDetails = authService.loadUserByMobile(mobile);
        if (!code.equals(userDetails.getPassword())) {
            throw new UsernameNotFoundException("短信验证码不正确");
        }

        MobileAuthenticationToken authenticationToken = new MobileAuthenticationToken(userDetails, userDetails.getAuthorities());
        authenticationToken.setDetails(unauthenticatedToken.getDetails());

        return authenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MobileAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
